/*
 * Copyright 2011 Cedric Priscal
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.serialport.sample;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import android.os.Bundle;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


public class Sending01010101Activity extends SerialPortActivity {
    private static final String TAG = "Sending01010101Activity";

    private TextView mMaxTextView;
    private RecyclerView mRecyclerView;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                String maxValue = (String) msg.obj;
                mMaxTextView.setText(maxValue);
            }
        }
    };
    private CustomAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sending01010101);
        mRecyclerView = findViewById(R.id.recycle_view);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 16));
        mAdapter = new CustomAdapter();
        mRecyclerView.setAdapter(mAdapter);
        mMaxTextView = findViewById(R.id.max_value);
    }

    @Override
    protected void onDataReceived(byte[] buffer, int size) {
        Log.i(TAG, "onDataReceived: ");
        final float[] data = buildData(buffer);
        mRecyclerView.post(new Runnable() {
            @Override
            public void run() {
                mAdapter.setData(data);
            }
        });


        float maxValue = Integer.MIN_VALUE;
        for (float value : data) {
            if (value > maxValue) {
                maxValue = value;
            }
        }

        Message message2 = mHandler.obtainMessage(1);
        message2.obj = String.format("%.2f", maxValue);
        mHandler.sendMessage(message2);
    }

    private float[] buildData(byte[] buffer) {
        float[] temperatureData = new float[64];
        for (int i = 3; i < buffer.length - 1; i += 2) {
            byte highData = buffer[i];
            byte lowData = buffer[i + 1];
            String highDataBinary = getBinaryString(highData);
            String lowDataBinary = getBinaryString(lowData);
            Integer valueOf = Integer.valueOf(lowDataBinary + highDataBinary, 2);
            float temperature = 1f * (valueOf - 400) / 10;
            temperatureData[(i - 3) / 2] = temperature;
        }
        return temperatureData;
    }

    private String getBinaryString(int data) {
        if (data < 0) {
            data += 256;
        }
        String lowDataBinaryStr = Integer.toBinaryString(data);
        int fillSize = 8 - lowDataBinaryStr.length();
        StringBuilder sb = new StringBuilder(lowDataBinaryStr);
        for (int i = 0; i < fillSize; i++) {
            sb.insert(0, "0");
        }
        return sb.toString();
    }

    private class CustomAdapter extends RecyclerView.Adapter<ItemHolder> {
        private float[] mData = new float[64];

        public void setData(float[] data) {
            System.arraycopy(data, 0, mData, 0, 64);
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public ItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new ItemHolder(parent.getContext(), R.layout.item_layout);
        }

        @Override
        public void onBindViewHolder(@NonNull ItemHolder holder, int position) {
            ((TextView) holder.itemView).setText(String.valueOf(mData[position]));
        }

        @Override
        public int getItemCount() {
            return mData.length;
        }
    }

    private class ItemHolder extends RecyclerView.ViewHolder {

        public ItemHolder(Context context, @LayoutRes int itemLayout) {
            super(LayoutInflater.from(context).inflate(itemLayout, null, false));
        }
    }

}
